<template>
	<view>
		<scroll-view :scroll-y="modalName==null" class="page" :class="modalName!=null?'show':''">
			<!-- <cu-custom bgColor="bg-gradual-pink" :isBack="true">
				<block slot="content">消息</block>
			</cu-custom> -->
			
			<div class="chat_info" ref="chat" :style="{height:clientHeight + 'px'}">
				<view v-for="item in chatContent" :key="item.id">
					<view class="time">{{ item.createTime }}</view>
					<view v-if="item.userId == userInfo.id" class="service_wrap">
						<view class="service_content">{{ item.content }}</view>
						<img style="margin-bottom: 0;" class="chat_img" :src="userInfo.avatar" alt="用户头像" srcset="">
					</view>
					<view v-if="item.userId != userInfo.id" class="customer_wrap">
						<img style="margin-top: 0;" class="chat_img" :src="toAvatar" alt="用户头像" srcset="">
						<view class="customer_content">{{ item.content }}</view>
					</view>
				</view>
			</div>
			<view class="send_info">
				<input class="ipt_syl" :value="chatVls" @input="getIptVls" />
				<view class="send_btn" @tap="sendInfo">发送</view>
			</view>
		</scroll-view>
	</view>

</template>

<script>
	import { recevoirMsg, sendMessage } from '../../../utils/api'
	import { baseURL } from '../../../utils/baseUrl';
	export default {
		name: 'message',
		data() {
			return {
				baseURL,
				pageNo:1,
				clientHeight: '',
				modalName: null,
				toUserId:'',
				toAvatar:'',
				currentId:'',
				currenAvatar:'',
				chatVls: '',
				currentUserId: '',
				userInfo:{},
				chatContent: [],// 用户聊天内容
			}
		},
		onLoad(options){
			this.toUserId = options.toUserId;
			this.toAvatar = options.toAvatar;
			let userInfo = uni.getStorageSync("userInfo");
			this.userInfo = userInfo;
			this.queryChatInfo();
		},
		onShow(){
			let userInfo = uni.getStorageSync("userInfo")
			this.userInfo = userInfo;
			uni.connectSocket({
				url: `ws://192.168.0.13:8181/websocket/${userInfo.id}`,
				header:{
					'content-type': 'application/json',
					'X-Access-Token':uni.getStorageSync("token") || ""
				},
				success() {
					console.log('WebSocket连接成功');
					uni.onSocketOpen(function (res) {
						console.log('WebSocket连接已打开！');
					});
					uni.onSocketError(function (res) {
						console.log('WebSocket连接打开失败，请检查！',res);
					});
					uni.onSocketMessage(function (res) {
						let message = JSON.parse(res.data)
						console.log('收到消息：', message);
					});
					// uni.onSocketClose(function () {
					// 	console.log('WebSocket连接已关闭');
					// });
				},
				fail(err) {
					console.error('WebSocket连接失败', err);
				}
			});
			uni.getSystemInfo({
			   success:(res=>{
				   console.log('res.windowHeight',res.windowHeight - 50)
					this.clientHeight = res.windowHeight-140
				})
			});
			this.scrollBottom()
		},
		
		mounted(){
			
			// this.queryChatInfo()
			// this.currentUserId = userInfo.id;
		},
		destroyed() {

		},
		
		methods: {	
			// 获取input值
			getIptVls(e){
				this.chatVls = e.target.value;
			},
			
			// 滚动到最底部
			scrollBottom(){
				// this.$nextTick(() => {
				  let msg = this.$refs.chat// 获取对象
				  console.log('msg==========================>',msg)
				//   msg.scrollTop = msg.scrollHeight // 滚动高度
				// })
			},
			
			// 查询聊天记录
			async queryChatInfo(){
				recevoirMsg(this.userInfo.id, this.toUserId, this.pageNo).then(childRes => {
					// console.log('childRes===========>',childRes)
					this.chatContent = childRes.result.records;
					this.scrollBottom();
				})
			},
			
			// 发送输入的值
			sendInfo(){
				const params = {
					content:this.chatVls,
					userId: this.userInfo.id,
					targetUserId: this.toUserId,
				}
				sendMessage(params).then(res => {
					console.log('发送的消息',res)
					if(res.code == 200){
						this.chatVls = ''
						this.queryChatInfo()
					}
				}).catch(err =>{
					console.error(err)
				})
				console.log('发送消息', this.chatVls)
			},
			
		}
	}
</script>

<style scoped lang="less">
	.send_info{
		display: flex;
		justify-content: space-between;
		width: 100%;
		height: 40px;
		background-color: #fff;
		position: fixed;
		bottom: 20rpx;
		.ipt_syl{
			height: 30px; 
			width: 86%; 
            margin-left: 30rpx;
            border-bottom: 1px solid #e9e9e9;
		}
		.send_btn{
			width: 12%; 
			height: 30px; 
			line-height: 30px;
			text-align: center;
			margin: 5px;
			border-radius: 4px;
			color: #fff;
			background-color: #1890ff;
		}
	}
	.chat_info{
		// margin-bottom: 50px;
		// height: 400px;
	    overflow-y: scroll;
	    .time{
	       text-align: center;
	        font-size: 12px;
	        font-family: PingFangSC-Regular, PingFang SC;
	        font-weight: 400;
	        color: rgba(0,0,0,0.45);
	        margin: 10px;
	    }
	    .service_wrap{
	        display: flex;
	        justify-content: flex-end;
	        align-items: end;
	        margin-top: 16px;
	        color: #fff;
	        .service_content{
	            padding: 10px;
	            background: linear-gradient(315deg, #5CB1FF 0%, #1890FF 100%);
	            border-radius: 8px 8px 0px 8px;
	        }
	    }
	    .customer_wrap{
	        display: flex;
	        align-items: start;
	        margin-top: 16px;
	        .customer_content{
	            padding: 10px;
	            background: #FFFFFF;
	            border-radius: 0px 8px 8px 8px;
	            border: 1px solid rgba(0,0,0,0.15);
	        }
	    }
	    .chat_img {
	        width: 28px;
	        height: 28px;
	        border-radius: 14px;
	        margin: 10px;
	    }
	}
</style>
